# author: Evan
# date: 18.Apr.2012


import cgi, cgitb
import os, sys

sys.path.append(os.path.join(os.path.dirname(__file__), 'lib'))

from urllib import urlencode
from urllib2 import urlopen
from urlparse import urlparse
from os import environ

import blablaurl

#
# -----------
# common data
# -----------


headers = {"Content-Type":"text/plain"}


#
# --------------------------------------------------------------------
# a function to return the file-like object use urlopen
# --------------------------------------------------------------------
def openUrl(urlAddr):
    return urlopen(urlAddr)


# 
# -----------------
# output to broswer
# -----------------
def outputToPage(str):
  for name, value in headers.iteritems():
    print name+":",value
  print ""
  print str





#--------------------------------------------------------------------
# begin
#--------------------------------------------------------------------
#--------------------------------------------------------------------
#--------------------------------------------------------------------




# get the url address from browser

form = cgi.FieldStorage()

urlAddr = form.getvalue("urlAddr")

# set common data

urlParseObj = urlparse(urlAddr)

blablaurl.domain = urlParseObj.scheme +"://"+urlParseObj.netloc



blablaurl.proxyAddr = "http://"+environ["HTTP_HOST"] +"/blabla/go?"



urlFile = openUrl(urlAddr)

type = urlFile.info().getheader("Content-Type")

headers["Content-Type"] = type 


# if html, then replace links


if "text" in type:
  s = urlFile.read()
  outputToPage(blablaurl.convertUrl(s))

else:
  outputToPage(urlFile.read())


